import React, { useState, useEffect } from 'react';
import NotesAPI from './api/NotesAPI';
import Sidebar from './sidebar/Sidebar';
import EditPanel from './editPanel/EditPanel';
import './App.css';

const App: React.FC = () => {
  const [notes, setNotes] = useState<Note[]>([]);
  const [activeNote, setActiveNote] = useState<Note | null>(null);

  useEffect(() => {
    refreshNotes();
  }, []);

  const refreshNotes = () => {
    const allNotes = NotesAPI.getAllNotes();
    setNotes(allNotes);
    if (allNotes.length > 0) {
      setActiveNote(allNotes[0]);
    }
  };

  const handleNoteSelect = (noteId: number) => {
    const selectedNote = notes.find((note) => note.id === noteId) || null;
    setActiveNote(selectedNote);
  };

  const handleNoteAdd = () => {
    const newNote = {
      id: Math.floor(Math.random() * 1000000),
      title: "新建笔记",
      body: "开始记录...",
      updated: new Date().toISOString(),
    };
    NotesAPI.saveNote(newNote);
    refreshNotes();
  };

  const handleNoteEdit = (title: string, body: string) => {
    if (activeNote) {
      const updatedNote = { ...activeNote, title, body, updated: new Date().toISOString() };
      NotesAPI.saveNote(updatedNote);
      refreshNotes();
    }
  };

  const handleNoteDelete = (noteId: number) => {
    NotesAPI.deleteNote(noteId);
    refreshNotes();
  };

  return (
    <div className="app">
        <div className="container" >
          <Sidebar
            activeNote={activeNote}       
            notes={notes} 
            onNoteSelect={handleNoteSelect} 
            onNoteAdd={handleNoteAdd} 
            onNoteDelete={handleNoteDelete} 
          />
          {
            notes.length > 0 && (
              <EditPanel 
                activeNote={activeNote} 
                onNoteEdit={handleNoteEdit} 
              />
            )
          }
      </div>
    </div>
  );
};

export default App;

interface Note {
  id: number;
  title: string;
  body: string;
  updated: string;
}
